<template>
  <div class="dict-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchDictVisible" inline size="mini" :model="searchDictForm" ref="searchDictForm" @keyup.enter.native="searchDictHandle">
        <el-form-item prop="type" label="字典检索">
          <el-select v-model="searchDictForm.type" filterable clearable placeholder="请选择检索的字典名称">
            <el-option
              v-for="dict in dictTypeList"
              :key="dict.value"
              :label="dict.name"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="word">
          <el-input v-model="searchDictForm.word" clearable placeholder="请输入检索的字典值标题"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchDictForm.status" clearable placeholder="请选择检索的字典状态">
            <el-option label="可用" value="0"></el-option>
            <el-option label="不可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchDictHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetSearchDictHandle" plain
                     icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="d-tool">
      <el-button :disabled="dataLoad" @click="openDictDialogHandle(undefined, false)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="dataLoad || dictSelection.length === 0" @click="deleteDictHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <right-tool-bar :search-visible="searchDictVisible" :search-load="dataLoad"
                      @toggle-search="searchDictVisible = !searchDictVisible" @refresh-table="getDictList" />
    </div>

    <el-table
      v-loading="dataLoad"
      element-loading-text="字典数据加载中"
      element-loading-spinner="el-icon-loading"
      highlight-current-row
      :data="dictList"
      :default-sort = "{ prop: searchDictForm.field, order: searchDictForm.order}"
      @sort-change="sortChangeHandle"
      @selection-change="(val) => this.dictSelection = val"
      ref="dictTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="名称"></el-table-column>
<!--      <el-table-column prop="type" header-align="center" align="center" label="类型"></el-table-column>-->
      <el-table-column prop="value" header-align="center" align="center" label="字典值" show-overflow-tooltip></el-table-column>
      <el-table-column prop="valueLabel" header-align="center" align="center" label="值标题"></el-table-column>
      <el-table-column prop="valueType" header-align="center" align="center" label="值类型" :formatter="typeFormat"></el-table-column>
      <el-table-column sortable :sort-orders="sortOrders" prop="sort" header-align="center" align="center" label="排序等级" width="100"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="更新时间"></el-table-column>
      <el-table-column prop="updateUser" header-align="center" align="center" label="更新用户"></el-table-column>
      <el-table-column sortable :sort-orders="sortOrders"  prop="createTime" header-align="center" align="center" label="创建时间" width="100"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template v-slot="scope">
<!--          <el-button type="text" size="small" @click="viewDictHandle(scope.row.id)">查看</el-button>-->
          <el-button type="text" icon="el-icon-edit" size="small" @click="openDictDialogHandle(scope.row, true)">修改</el-button>

          <el-dropdown :disabled="loading">
            <span class="el-dropdown-link fz12" v-bind:style="{ color: themeColor, marginLeft: '7px' }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-show="scope.row.status === 1" icon="el-icon-check" @click.native="updateDictStatusHandle(scope.row, 0)">
                使用
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 0" icon="el-icon-close" @click.native="updateDictStatusHandle(scope.row, 1)">
                禁用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteDictHandle(scope.row)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 系统字典操作弹出框 -->
    <dict-save-update :dialog-visible="optDictDialog" :dict-type-list="dictTypeList" ref="optDictDialog"
                      @close-dict-dialog="closeDictDialogHandle" />

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import DictSaveUpdate from "@/components/dict/save-update";

  export default {
    layout: 'admin',
    name: "admin-system-dict",
    components: { RightToolBar, DictSaveUpdate },
    data () {
      return {
        // 系统字典数据列表
        dictList: [],
        // 系统字典类型数据列表
        dictTypeList: [],
        // 系统字典表格被选中的数据
        dictSelection: [],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 字典检索是否显示
        searchDictVisible: true,
        // 字典检索表单对象
        searchDictForm: {
          // 字典类型
          type: '',
          // 字典值标题
          word: '',
          // 字典状态
          status: '',
          // 排序字段
          field: 'sort',
          // 排序方式
          order: 'ascending'
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前系统字典数量
        totalNum: 0,
        // 系统字典操作弹出框是否显示[true-显示 false-关闭]
        optDictDialog: false,
        // 系统字典查看弹出框是否显示[true-显示 false-关闭]
        viewDictDialog: false,
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    activated () {
      // this.getDataList()
    },
    created() {
      if (process.client) {
        // 初始化表格数据
        this.getDictList()
        // 初始化系统字典类型数据列表
        this.getDictTypeList()
      }
    },
    methods: {
      /**
       * 系统字典检索事件
       */
      searchDictHandle() {
        this.pageIndex = 1
        this.getDictList()
      },
      /**
       * 重置系统字典检索表单对象事件
       */
      resetSearchDictHandle() {
        let searchDictForm = this.searchDictForm
        if (searchDictForm.type === '' && searchDictForm.word === '' && searchDictForm.status === '') {
          this.notify('info', "温馨提示", '所有查询条件为空')
          return
        }
        searchDictForm.type = ''
        searchDictForm.word = ''
        searchDictForm.status = ''
        // 重新获取表格数据
        this.getDictList()
      },
      /**
       * 获取系统字典数据列表方法
       */
      getDictList () {
        let searchDictForm = this.searchDictForm
        let formObj = {
          type: searchDictForm.type,
          word: searchDictForm.word,
          status: searchDictForm.status,
          field: searchDictForm.field,
          order: searchDictForm.order,
          page: this.pageIndex,
          limit: this.pageSize
        }
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/sys/dict/page/list', formObj)
          .then(({ data:page }) => {
            this.dictList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      /**
       * 获取系统字典类型数据列表方法
       */
      getDictTypeList() {
        this.$axios.$get('/sys/dict/type/list')
          .then(({ data }) => {
            this.dictTypeList = data
          })
          .catch(() => {});
      },
      /**
       * 表格数据排序方式变化事件
       * @param {string} prop  排序字段
       * @param {string} order 排序方式
       */
      sortChangeHandle( { prop, order } ) {
        this.pageIndex = 1
        this.searchDictForm.field = prop
        this.searchDictForm.order = order
        this.getDictList()
      },
      /**
       * 每页显示个数变化事件
       * @param val 最新每页显示个数
       */
      sizeChangeHandle (val) {
        this.pageIndex = 1
        this.pageSize = val
        this.getDictList()
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param val 最新页码数值
       */
      currentChangeHandle (val) {
        if (this.pageIndex === val) {
          return
        }
        this.pageIndex = val
        this.getDictList()
      },
      /**
       * 打开系统字典操作弹出框事件
       * @param {Object}  dict    系统字典对象
       * @param {boolean} optType 系统字典操作类型[false-添加 true-修改]
       */
      openDictDialogHandle(dict, optType) {
        this.optDictDialog = true

        this.$nextTick(() => {
          this.$refs.optDictDialog.initDictDialog(dict, optType)
        })
      },
      /**
       * 关闭系统字典操作弹出框事件
       * @param {boolean} bool true-刷新表格数据 false-不刷新表格数据
       */
      closeDictDialogHandle(bool) {
        this.optDictDialog = false

        if (bool) {
          this.getDictList()

          if (this.dictSelection.length > 0) {
            // 如果选中行不为空，则清空表格选中行
            this.$refs.dictTable.clearSelection()
          }
        }
      },
      /**
       *
       * @param dict
       */
      viewDictHandle(dict) {

      },
      /**
       * 更新字典状态事件
       * @param {Object} dict   字典对象
       * @param {Number} status 最新状态
       */
      updateDictStatusHandle(dict, status) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$post('/sys/dict/update/status', { id: dict.id, type: dict.type, status: status })
          .then(() => {
            // 变更字典状态
            dict.status = status;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      /**
       * 系统字典删除事件
       * @param {Object} dict 系统字典对象
       */
      deleteDictHandle (dict) {
        let names = [], requestBody = { dictIdList: [], typeList: [] };
        if (!!dict) {
          names.push(dict.name);
          requestBody.dictIdList.push(dict.id);
          requestBody.typeList.push(dict.type);
        } else {
          let dictSelection = this.dictSelection
          let length = dictSelection.length
          for (let i = 0; i < length; i++) {
            let dict = dictSelection[i]
            names.push(dict.name)
            requestBody.dictIdList.push(dict.id);
            requestBody.typeList.push(dict.type);
          }
        }

        this.$confirm(`确定要删除[${names}]字典吗?`, '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          // 表格数据加载
          this.dataLoad = true
          this.$axios.$delete('/sys/dict/delete', { data: requestBody })
            .then(() => {
              this.notify('success', '操作成功', `成功删除[${names}]字典数据`)
              // 重新加载数据
              this.getDictList()
            })
            .catch(() => {})
            .finally(() => {
              // 表格数据加载结束
              this.dataLoad = false
            })

        })
        .catch(() => {
          this.notify('success', '温馨提示', '系统字典删除操作取消')
        })
      },
      /**
       * 字典值类型枚举映射
       * @param {Object} row 系统字典对象
       */
      typeFormat(row) {
        switch (row.valueType) {
          case 0:
            return "string"
          case 1:
            return "json"
          case 2:
            return 'json-array'
          default:
            return '未知字典类型'
        }
      }
    }
  }
</script>

<style scoped>
  .dict-page .d-tool {
    margin-bottom: 7px;
  }
  .dict-page .paging {
    float: right;
    margin: 7px;
  }
</style>
